Writing your first Django app, part 1
By Adrian Holovaty <holovaty@gmail.com>
Let's learn by example.
Throughout this tutorial, we'll walk you through the creation of a simple Web poll application.
It'll consist of two parts:
- A public site that lets people vote in polls and view poll results.
- An admin site that lets you add, change and delete polls behind the scenes.
We'll assume you have Django installed already.
Initial setup
If this is your first time using Django, you'll have to take care of some initial setup.
Run the command django-admin.py startproject myproject. That'll create a myproject directory in your current directory.
(django-admin.py should be on your system path if you installed Django via its setup.py utility. If it's not on your path, you can find it in site-packages/django/bin; consider symlinking to it from some place on your path, such as /usr/local/bin.)
A project is a collection of settings for an instance of Django -- including database configuration, Django-specific options and application-specific settings. Let's look at what startproject created:
myproject/
__init__.py
apps/
__init__.py
settings.py
urls.py
First, edit myproject/settings.py. It's a normal Python module with module-level variables representing Django settings. Edit the file and change these settings to match your database's connection parameters:
- DATABASE_ENGINE -- Either 'postgresql', 'mysql' or 'sqlite3'. More coming soon.
- DATABASE_NAME -- The name of your database, or the full (absolute) path to the database file if you're using sqlite.
- DATABASE_USER -- Your database username (not used for sqlite).
- DATABASE_PASSWORD -- Your database password (not used for sqlite).
- DATABASE_HOST -- The host your database is on. Leave this as an empty string if your database server is on the same physical machine (not used for sqlite).
Note
Make sure you've created a database within PostgreSQL or MySQL by this point. Do that with "CREATE DATABASE database_name;" within your database's interactive prompt.
Now, take a second to make sure myproject is on your Python path. You can do this by copying myproject to Python's site-packages directory, or you can do it by altering the PYTHONPATH environment variable. See the Python path documentation for more information. If you opt to set the PYTHONPATH environment variable, note that you'll need to set it to the parent directory of myproject. (You can test this by typing "import myproject" into the Python interactive prompt.)
Run the following command:
django-admin.py init --settings=myproject.settings
The django-admin.py utility generally needs to know which settings module you're using. Here, we're doing that by specifying settings= on the command line, but that can get tedious. If you don't want to type settings= each time, you can set the DJANGO_SETTINGS_MODULE environment variable. Here's how you do that in the Bash shell on Unix:
export DJANGO_SETTINGS_MODULE=myproject.settings
On Windows, you'd use set instead:
set DJANGO_SETTINGS_MODULE=myproject.settings
If you don't see any errors after running django-admin.py init, you know it worked. That command initialized your database with Django's core database tables. If you're interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), or .schema (SQLite) to display the tables.
Creating models
Now that your environment -- a "project" -- is set up, you're set to start doing work. (You won't have to take care of this boring administrative stuff again.)
Each application you write in Django -- e.g., a weblog system, a database of public records or a simple poll app -- consists of a Python package, somewhere on your Python path, that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
In this tutorial, we'll create our poll app in the myproject/apps directory, for simplicity. As a consequence, the app will be coupled to the project -- that is, Python code within the poll app will refer to myproject.apps.polls. Later in this tutorial, we'll discuss decoupling your apps for distribution.
To create your app, change into the myproject/apps directory and type this command:
django-admin.py startapp polls
(From now on, this tutorial will leave out the --settings parameter and will assume you've either set your DJANGO_SETTINGS_MODULE environment variable or included the --settings option in your call to the command.)
That'll create a directory structure like this:
polls/
__init__.py
models/
__init__.py
polls.py
views.py
This directory structure will house the poll application.
The first step in writing a database Web app in Django is to define your models -- essentially, your database layout, with additional metadata.
Philosophy
A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you're storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it.
In our simple poll app, we'll create two models: polls and choices. A poll has a question and a publication date. A choice has two fields: the text of the choice and a vote tally. Each choice is associated with a poll.
These concepts are represented by simple Python classes. Edit the polls/models/polls.py file so it looks like this:
from django.core import meta
class Poll(meta.Model):
question = meta.CharField(maxlength=200)
pub_date = meta.DateTimeField('date published')
class Choice(meta.Model):
poll = meta.ForeignKey(Poll)
choice = meta.CharField(maxlength=200)
votes = meta.IntegerField()
The code is straightforward. Each model is represented by a class that subclasses django.core.meta.Model. Each model has a number of class variables, each of which represents a database field in the model.
Each field is represented by an instance of a meta.*Field class -- e.g., meta.CharField for character fields and meta.DateTimeField for datetimes. This tells Django what type of data each field holds.
The name of each meta.*Field instance (e.g. question or pub_date ) is the field's name, in machine-friendly format. You'll use this value in your Python code, and your database will use it as the column name.
You can use an optional first positional argument to a Field to designate a human-readable name. That's used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn't provided, Django will use the machine-readable name. In this example, we've only defined a human-readable name for Poll.pub_date. For all other fields in this model, the field's machine-readable name will suffice as its human-readable name.
Some meta.*Field classes have required elements. meta.CharField, for example, requires that you give it a maxlength. That's used not only in the database schema, but in validation, as we'll soon see.
Finally, note a relationship is defined, using meta.ForeignKey. That tells Django each Choice is related to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
Activating models
That small bit of model code gives Django a lot of information. With it, Django is able to:
- Create a database schema (CREATE TABLE statements) for this app.
- Create a Python database-access API for accessing Poll and Choice objects.
But first we need to tell our project that the polls app is installed.
Philosophy
Django apps are "pluggable": You can use an app in multiple projects, and you can distribute apps, because they don't have to be tied to a given Django installation.
Edit the myproject/settings.py file again, and change the INSTALLED_APPS setting to include the string "myproject.apps.polls". So it'll look like this:
INSTALLED_APPS = (
'myproject.apps.polls',
)
(Don't forget the trailing comma because of Python's rules about single-value tuples.)
Now Django knows myproject includes the polls app. Let's run another command:
django-admin.py sql polls
(Note that it doesn't matter which directory you're in when you run this command.)
You should see the following (the CREATE TABLE SQL statements for the polls app):
BEGIN;
CREATE TABLE polls_polls (
id serial NOT NULL PRIMARY KEY,
question varchar(200) NOT NULL,
pub_date timestamp with time zone NOT NULL
);
CREATE TABLE polls_choices (
id serial NOT NULL PRIMARY KEY,
poll_id integer NOT NULL REFERENCES polls_polls (id),
choice varchar(200) NOT NULL,
votes integer NOT NULL
);
COMMIT;
Note the following:
- Table names are automatically generated by combining the name of the app (polls) with a plural version of the object name (polls and choices). (You can override this behavior.)
- Primary keys (IDs) are added automatically. (You can override this, too.)
- Django appends "_id" to the foreign key field name, by convention. Yes, you can override this, as well.
- The foreign key relationship is made explicit by a REFERENCES statement.
- It's tailored to the database you're using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key (SQLite) are handled for you automatically. The author of this tutorial runs PostgreSQL, so the example output is in PostgreSQL syntax.
If you're interested, also run the following commands:
- django-admin.py sqlinitialdata polls -- Outputs the initial-data inserts required for Django's admin framework.
- django-admin.py sqlclear polls -- Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
- django-admin.py sqlindexes polls -- Outputs the CREATE INDEX statements for this app.
- django-admin.py sqlall polls -- A combination of 'sql' and 'sqlinitialdata'.
Looking at the output of those commands can help you understand what's actually happening under the hood.
Now, run this command to create the database tables for the polls app automatically:
django-admin.py install polls
Behind the scenes, all that command does is take the output of django-admin.py sqlall polls and execute it in the database pointed-to by your Django settings file.
Read the django-admin.py documentation for full information on what this utility can do.
Playing with the API
Now, make sure your DJANGO_SETTINGS_MODULE environment variable is set (as explained above), and open the Python interactive shell to play around with the free Python API Django gives you:
# Modules are dynamically created within django.models. # Their names are plural versions of the model class names. >>> from django.models.polls import polls, choices # No polls are in the system yet. >>> polls.get_list() [] # Create a new Poll. >>> from datetime import datetime >>> p = polls.Poll(question="What's up?", pub_date=datetime.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's up?" >>> p.pub_date datetime.datetime(2005, 7, 15, 12, 00, 53) # Change values by changing the attributes, then calling save(). >>> p.pub_date = datetime(2005, 4, 1, 0, 0) >>> p.save() # get_list() displays all the polls in the database. >>> polls.get_list() [<Poll object>]
Wait a minute. <Poll object> is, utterly, an unhelpful representation of this object. Let's fix that by editing the polls model (in the polls/models/polls.py file) and adding a __repr__() method to both Poll and Choice:
class Poll(meta.Model):
# ...
def __repr__(self):
return self.question
class Choice(meta.Model):
# ...
def __repr__(self):
return self.choice
It's important to add __repr__() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin.
Note these are normal Python methods. Let's add a custom method, just for demonstration:
class Poll(meta.Model):
# ...
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
Note import datetime wasn't necessary. Each model method has access to a handful of commonly-used variables for convenience, including the datetime module from the Python standard library.
Let's jump back into the Python interactive shell:
>>> from django.models.polls import polls, choices
# Make sure our __repr__() addition worked.
>>> polls.get_list()
[What's up?]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> polls.get_object(id__exact=1)
What's up?
>>> polls.get_object(question__startswith='What')
What's up?
>>> polls.get_object(pub_date__year=2005)
What's up?
>>> polls.get_object(id__exact=2)
Traceback (most recent call last):
...
PollDoesNotExist: Poll does not exist for {'id__exact': 2}
>>> polls.get_list(question__startswith='What')
[What's up?]
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to polls.get_object(id__exact=1).
>>> polls.get_object(pk=1)
What's up?
# Make sure our custom method worked.
>>> p = polls.get_object(pk=1)
>>> p.was_published_today()
False
# Give the Poll a couple of Choices. Each one of these method calls does an
# INSERT statement behind the scenes and returns the new Choice object.
>>> p = polls.get_object(pk=1)
>>> p.add_choice(choice='Not much', votes=0)
Not much
>>> p.add_choice(choice='The sky', votes=0)
The sky
>>> c = p.add_choice(choice='Just hacking again', votes=0)
# Choice objects have API access to their related Poll objects.
>>> c.get_poll()
What's up?
# And vice versa: Poll objects get access to Choice objects.
>>> p.get_choice_list()
[Not much, The sky, Just hacking again]
>>> p.get_choice_count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want. There's no limit.
# Find all Choices for any poll whose pub_date is in 2005.
>>> choices.get_list(poll__pub_date__year=2005)
[Not much, The sky, Just hacking again]
# Let's delete one of the choices. Use delete() for that.
>>> c = p.get_choice(choice__startswith='Just hacking')
>>> c.delete()
For full details on the database API, see our Database API reference.
When you're comfortable with the API, read part 2 of this tutorial to get Django's automatic admin working.
Comments
Jaroslaw Zabiello July 18, 2005 at 6:27 p.m.
Sometimes there is a need for using unix_socket instead of tcp-ip port. Use syntax DATABASE_UNIXSOCKET=/tmp/mysql.sock and replace cursor() (DatabaseWrapper class in django/core/db/backends/mysql.py) with the following code:
http://rafb.net/paste/results/tknfpy12.h...
anonymous coward July 19, 2005 at 1:07 p.m.
For those that aren't accustomed with Python: don't try to name your project 'test' :) I just debugged 30 minutes (it couldn't find test.settings.main) before I realized that 'test' is builtin module in Python :) Of course this builtin module doesn't have settings.main :)
Will Gunadi July 19, 2005 at 4:33 p.m.
This is truly an eye-opener. Good job guys. It's about time Python to have a rapid web-development framework.
However one Postgresql-specific advise, please add "Without OIDS" when creating the mode tables.
Consuming the unique id's is not a good idea for tables that are designed to contain data.
I don't know why they (postgres people) defaults to WITH OIDS.
Will Gunadi July 19, 2005 at 4:34 p.m.
Sorry, I meant "model tables" not "mode tables" in my previous post.
dp_wiz July 25, 2005 at 2:27 p.m.
Just finished translating first tutorial into russian:
http://aenor.ru/wiz/django/tutorial_1
everes July 30, 2005 at 9:05 a.m.
I have translated the tutorial into Japanese freely.
http://www.everes.net/cgi-bin/trac.cgi/w...
http://www.everes.net/cgi-bin/trac.cgi/w...
Is there any problem?
yacc August 3, 2005 at 8:53 a.m.
Please mention, that the module name of the model file must
be included in myproject/apps/polls/models/__init__.py.
By default it contains only the appname, and one calls the file differently one gets only huge tracebacks ;)
Andreas
Uzair August 13, 2005 at 11:57 a.m.
Might want to add a bit of text to note that you can run
c = p.add_choice(choice='Just hacking again', votes=0)
ad nauseum, and end up with many identical choices. Of course, the way to get rid of them:
c_list = p.get_choice_list (choice__startswith="Just")
for c in c_list:
c.delete()
Nice work so far :)
geoffDeGeoffGeoff August 14, 2005 at 11:11 a.m.
what do you do if you have two columns that are both foreign keys of the same table?
Robin Munn August 14, 2005 at 6:43 p.m.
geoffDeGeoffGeoff -
You want the "rel_name" option of ForeignKey: see http://www.djangoproject.com/documentati... for details. Basically, you give a different rel_name to each of the two columns, and those two names will be used throughout the Django model API and in the database.
Brendan O'Connor August 21, 2005 at 12:57 a.m.
What's the conceptual distinction between a project and an application? What are some examples?
Uzair August 21, 2005 at 5:19 p.m.
Seems a 'project' represents a full-blown website. An 'application' represents a potentially re-usable module that can be plugged into a website.
As an example, suppose you were writing a portal "MyPortal". The homepage can be customized to display weather information, headlines, RSS feeds etc. You would model this with a project named 'MyPortal', and separate applications for the weather information, headlines, etc.
garthk August 21, 2005 at 7:25 p.m.
That's the convention I'm using.
jps September 5, 2005 at 10:44 a.m.
Hi. When setting up p = polls.Poll(), shouldn't that be "datetime.datetime.now()" (), and doesn't the datetime need explicit importing? (Python 2.4, WinXP)
funny_falcon September 5, 2005 at 10:52 a.m.
Do you exchange expierence with SQLObject project? Why (if not)?
And your template library is cool.
liNOOBux September 7, 2005 at 3:08 a.m.
It'd be nice to be able to see the entire example running on a website - anyone have a URL?
I'm trying to install Django on a fresh Fedora Core 4 installation, and this is *not* intuitive!
LiNOOBux September 7, 2005 at 3:53 a.m.
Any ideas on this error?
Mod_python error: "PythonHandler django.core.handlers.modpython"
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch
log=debug)
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 454, in import_module
f, p, d = imp.find_module(parts[i], path)
ImportError: No module named django
liNOOBux September 7, 2005 at 3:55 a.m.
It might be related to the fact that I can't get the database initialized:
# django-admin.py init --settings=myproject.settings.main
Error: The database couldn't be initialized. Here's the full exception:
(1045, "Access denied for user 'dbuser'@'localhost' (using password: YES)")
abc September 9, 2005 at 8:20 p.m.
"DATABASE_HOST -- The host your database is on. Leave this as an empty string if your database server is on the same physical machine (not used for sqlite)."
With this setting, I got a "Protocol Not Supported" error at the django-admin.py init command on Windows XP with PostgreSQL. Changing it from blank to
DATABASE_HOST = 'localhost'
worked.
Just in case anyone else sees the same thing.
berlinbrown October 1, 2005 at 6:53 p.m.
One thing that might help people building web-applications. Where does it say to actually hit the browser and launch the application.
berlinbrown October 1, 2005 at 7:11 p.m.
Also, does anybody get this error:
BEGIN;
Traceback (most recent call last):
File "django-admin.py", line 128, in ?
main()
File "django-admin.py", line 121, in main
output = ACTION_MAPPING[action](mod)
File "/usr/lib/python2.3/site-packages/django-1.0.0-py2.3.egg/django/core/management.py", line 56, in get_sql_create
for klass in mod._MODELS:
AttributeError: 'module' object has no attribute '_MODELS'
boscomonkey October 14, 2005 at 7:01 p.m.
If you're using MySQL with named pipes instead of TCP/IP, change the DATABASE_HOST in main.py to '.' instead of 'localhost'
I.e.,
DATABASE_HOST = '.'
Levi Cook October 16, 2005 at 9:26 a.m.
Working through this tutorial was pretty smooth. I would find it helpful (and suspect others might too) if you could avoid using the same name for different kinds of objects in the tutorial. In partiuclar, it took me a while to accurately grok how the name 'polls' was overloaded.
In production code, it might be be pedantic to name an application 'pollsapp' (or something similar). In tutorial code, however, it can provide some clarity in new terrain. Consider the following imports as an example:
from django.models.polls import polls, choices
from django.models.pollsapp import polls, choices
There's a lot of magic happening here. Django users are dynamically extending the django.models package on a per application basis, but the first import doesn't "emphasize" this strongly enough IMO.
Oh, and thanks for the awesome tools!
Arthur Hebert November 9, 2005 at 3:29 p.m.
I am getting the same error as boscomonkey, except when using django-admin.py:
django-admin.py init --settings=project1.settings
Error: The database couldn't be initialized.
'module' object has no attributes 'INSTALLED_APPS'
I get the same error if I give it a totall bogus settings flag, like
django-adming.py init --settings=foo.bar
which leads me to believe that the problem is occuring before anything that I have customized. I have created and empty database already for django to build on.
A previous problem that I had was an error that I don't have the postgre module installed (because I'm using mysql). I had set the DATABASE_ENGINE in my project settings to 'mysql', but the default 'postgresql' was still set in the global settings. The error went away when I changed the global settings parameter. Interesting (maybe a bug?) that it checks for appropriate modules before overriding the global settings with the local settings.
So far as I can tell, my call to django-admin.py isn't even getting to my project's settings before it has an error. Any ideas?
Tristan November 9, 2005 at 7 p.m.
Arthur Herbert,
I had this, then I realised that django and the tutorial had been changed since I got the django source - the older version I had had the settings module in a directory, the newer version has it solely in a file. Try getting the latest source. It seems to work with that.
Arthur Hebert November 10, 2005 at 3:17 a.m.
Tristan, thanks for the reply. I did see something about that in an earlier post, but I do have the latest source and I see no settings directory.
I've started to put print statements in the code whenever I have a few spare minutes. At this moment, it looks like the error occurs in django/core/meta/__init__.py in the get_app() method. Specifically, it is a call from django/core/management.py to meta.get_app('auth'). Something goes awry with the __import__() statement, but I haven't dug any farther than that.
felix November 10, 2005 at 5:23 a.m.
Same as you Arthur Herbert.
My settings file says 'mysql' but when running django-admin it complains of postgresql problems
cruxnu:~/Sites/djangotest cruxxial$ ls
myproject
cruxnu:~/Sites/djangotest cruxxial$ django-admin.py init --settings=myproject.settings
Error: The database couldn't be initialized.
Could not load database backend: No module named psycopg. Is your DATABASE_ENGINE setting (currently, 'postgresql') spelled correctly?
so its not actually finding the settings.
i'll post to the users list.
panos November 10, 2005 at 8:42 a.m.
reagarding the following error:
Error: The database couldn't be initialized.
'module' object has no attribute 'INSTALLED_APPS'
I got it to, but then I tried the option with the enironment variable DJANGO_SETTINGS_MODULE and it worked.
So try
1. export DJANGO_SETTINGS_MODULE=myproject.settings
2. django-admin.py init
and hopefully it will work for you
felix November 10, 2005 at 10:15 a.m.
wow, that did work.
i wonder why ?
Arthur Hebert November 10, 2005 at 12:37 p.m.
Wow, that worked for me too! That's odd, because I checked, and the code *is* setting the DJANGO_SETTINGS_MODULE env variable. Or, at least I can retrieve it in the code from the os.environ dictionary. Very strange.
Thank you Panos!
felix November 16, 2005 at 6:03 a.m.
The tutorial says that you COULD if you wanted to export DJANGO_SETTINGS_MODULE
but it seems that you HAVE to do so.
NoS November 17, 2005 at 2:05 a.m.
Is there a list where 's' are appended. For example, class Poll and Choice create models polls and choices. Used as:
>>> from django.models.polls import polls, choices
(How to, or) Any option to not append 's' to application and object names in SQL table ? For example, poll_poll instead of polls_polls.
Please consider not appending 's'. Thank you!
Adrian Holovaty November 17, 2005 at 8:20 a.m.
NoS: See the db_table option.
NoS November 18, 2005 at 2:46 a.m.
Thank you Adrian for the documentation pointer to the META option of db_table. Will use it.
Any hint or environment variable setting to specify the model name ? For example, class News(meta.Model) ... became Newss in the admin interface and ... import newss in Python.
Thank you!
Adrian Holovaty November 18, 2005 at 9:10 a.m.
NoS: See verbose_name_plural and module_name, both of which are META options.
Russell Keith-Magee November 18, 2005 at 6:51 p.m.
It's worth noting that if you use camel case for attribute names on database objects (i.e., naming an attribute deliveryDate rather than delivery_date) you might encounter some problems when you get to a raw database prompt.
Django handles the case properly; however, the PostgreSQL prompt converts all input to lower case. As a result, the command:
select myOrder.deliveryDate from myOrder;
gets converted to:
select myorder.deliverydate from myorder;
which doesn't match the field/table names that Django creates. If you need to get into the database manually to tweak/experiment with queries, you will need to use quotes to 'escape' the upper case fields:
select "myOrder"."deliveryDate" from "myOrder";
I believe MySQL has a similar problem, but requires the use of back ticks rather than quotes.
MySZ November 23, 2005 at 3:55 p.m.
Hello
I'm new in Django, and for a practice, I translate this tutorial (it mean first part of it) to polish. My translation is at http://diary.urzenia.net/wp-content/djan...
Post a comment
Note: Please only use the comments for questions/critcisms/suggestions on the docs; if you experience errors please file a ticket, ask in the IRC channel, or post to the django-users list. Comments will be periodically reviewed, integrated into the documentation proper, and removed.

Jaroslaw Zabiello July 18, 2005 at 6:15 p.m.
For using non-standard port you can use syntax DATABASE_PORT=3309 but then you need to replace cursor() method from DatabaseWrapper class (in django/core/db/backends/mysql.py) to the following code: http://rafb.net/paste/results/PW0yz599.h...